package com.cans.base.web;

import com.cans.base.dto.ResDto;
import com.cans.base.model.FileDetail;
import com.cans.base.service.api.IFileDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author cans
 * @date 2018/6/4
 * @description 文件操作web层
 */
@Controller
@RequestMapping("/file")
public class FileDetailController {

    private Logger logger = LoggerFactory.getLogger(FileDetailController.class);

    @Resource
    private IFileDetailService fileDetailService;


    /**
     * 文件上传
     * @return
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    public ResDto upload(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResDto.fait("文件为空");
        }

        return ResDto.success(fileDetailService.saveFile(file));

    }

    /**
     * 文件下载
     * @return
     */
    @GetMapping(value = "/download/{id}")
    public void download(@PathVariable String id, HttpServletResponse response){

        FileDetail fileDetail = fileDetailService.findOne(id);

        File file = new File(fileDetail.getUrl());
        //判断文件父目录是否存在
        if(file.exists()){
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileDetail.getFileName());

            byte[] buffer = new byte[1024];
            //文件输入流
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            //输出流
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

                os.flush();

            } catch (Exception e) {
                logger.error("",e);
            }finally {
                try {
                    assert bis != null;
                    bis.close();
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    logger.error("流关闭异常",e);
                }
            }

        }

    }
}
